package com.mk.zookeeper.demo.enent;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.AddWatchMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ZkEnvent {
    @Autowired
    private ZooKeeper zooKeeper;

    /**
     * 只监听一次
     * @param node 节点名称，以/号开头
     * @throws KeeperException
     * @throws InterruptedException
     */
    public void getData(String node) throws KeeperException, InterruptedException {
        Stat stat = new Stat();
        zooKeeper.getData(node,(x) -> {
            log.info(x.getState().name());
            log.info(x.getType().name());
            log.info(x.getPath());
            log.info(stat + "");
            Watcher.Event.EventType type = x.getType();
        }, stat);
    }

    /**
     * 只监听一次
     * 监听类型：创建、删除、修改
     * @param node 节点名称，以/号开关
     * @throws KeeperException
     * @throws InterruptedException
     */
    public void exists(String node) throws KeeperException, InterruptedException {
        zooKeeper.exists(node, (x) -> {
           log.info("exists");
           log.info(x.getPath());
        });
    }

    /**
     * 循环监听
     * @param node 节点名称
     *
     * AddWatchMode.PERSISTENT:：监听该节点的变化，包含孩子节点的创建和删除，但是孩子节点修改则不会被监听到.
     * AddWatchMode.PERSISTENT_RECURSIVE：监听该节点的变化，包含孩子节点的创建和删除和修改值。
     * @throws KeeperException
     * @throws InterruptedException
     */
    public void addWatch(String node) throws KeeperException, InterruptedException {
        zooKeeper.addWatch(node, (x) -> {
            log.info(x.getState().name());
            log.info(x.getType().name());
            log.info(x.getPath());
            log.info(x + "");
        }, AddWatchMode.PERSISTENT_RECURSIVE);
    }
}
